<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * 获得平台通信验证文件名称
 */
function get_platform_check_data($customer_id) {
    if (!$customer_id)
        return false;
    $data = M('customer')->find($customer_id);
    $data_name = 'SH_' . substr(base64_encode(md5(substr($data['key'], 0, 5))), 0, 25);
    return $data_name;
}

/**
 * 金额格式认证
 * @param float $price 金额
 */
function checkMoney($price) {
    return preg_match('/^[0-9]+(\.[0-9]{1,2})?$/is', $price);
}

/**
 * 弹出框错误提示并且关闭弹出框
 * @param string $msg 错误提示信息
 */
function tipsDivError($msg , $type = 'error' , $data = '') {
    if (!$msg)
        return false;
    echo "<script>parent.zeroModal.{$type}({content: '{$msg}',buttons: [{ className: 'zeromodal-btn zeromodal-btn-primary', name: '确认', fn:function(){ {$data} parent.zeroModal.closeAll(); }} ]});</script>";
    exit;
}

/**
 * 获得支付实例化对象
 * @param int $pay_id 
 */
function paymentInfo($pay_id) {
    if (!$pay_id)
        return false;
    $payInfo = M('payment_config')->where(array('id' => $pay_id))->find();
    if (!$payInfo) {
        return false;
    }

    $info = unserialize($payInfo['info']);

    switch ($payInfo['type']) {
        case "1" :
            $obj_name = 'Alipay';
            break;
        case "2" :
            $obj_name = "Weixin";
            break;
    }
    $object_name = '\\Api\\Extend\\Payment\\' . ucfirst($obj_name); //组合空间命名
    return array('object_name' => $obj_name, 'object' => new $object_name($info));
}

/**
 * 获得分销商支付提供给供应商订单显示总金额
 * @param int $ref 订单编号
 */
function supplyOrderTotal($ref, $supply_customer_id) {
    if (!$ref)
        return '0';
    $order_line = M('order_line')->where(array('ref' => $ref, 'supply_customer_id' => $supply_customer_id))->field('supply_price,num,fee')->select();
    if (!$order_line)
        return '0';
    $total = 0;
    foreach ($order_line as $key => $value) {
        $total += ( $value['supply_price'] * $value['num'] ) + $value['fee'];
    }
    return $total;
}

/**
 * 获得商品供应最小价格
 */
function getSupplyPriceSmall($goods_id) {
    if (!$goods_id)
        return '0';
    return M('goods_supply')->where(array('goods_id' => $goods_id))->order('acting_price ASC')->getField('acting_price');
}

/**
 * 获得商品供应最大价格
 */
function getSupplyPriceMax($goods_id) {
    if (!$goods_id)
        return '0';
    return M('goods_supply')->where(array('goods_id' => $goods_id))->order('acting_price DESC')->getField('acting_price');
}

/**
 * 添加系统信息
 * @param int $customer_id
 * @param string $title
 * @param string $msg
 * @param int $role
 */
function insertSystemInfo($customer_id, $title, $msg, $role = 1) {
    if (!$msg || !$customer_id)
        return false;
    M('system_message')->add(array(
        'role' => 1,
        'target_id' => $customer_id,
        'title' => $title,
        'content' => $msg,
        'create_time' => date('Y-m-d H:i:s')
    ));
    return true;
}

/**
 * 升级检测
 * @param int $customer_id 
 * @param int $empirical
 */
function upgradeCheck($customer_id, $empirical) {
    if (!$customer_id || !$empirical)
        return false;
    $customer_info = M('customer')->where(array('id' => $customer_id))->find(); //获得商家原始经验
    $customer_empirical = $customer_info['empirical'] + $empirical; //合并经验
    $save_data = array('empirical' => $customer_empirical); //增加总经验
    $grade_info = M('grade')->where('`value` <= ' . $customer_empirical)->find();
    if (!$grade_info)
        return false;
    $save_data['grade_id'] = $grade_info['id']; //赋予新的用户组
    M('customer')->where(array('id' => $customer_id))->save($save_data); //数据修改
    if ($customer_info['grade_id'] != $grade_info['id']) {
        insertSystemInfo($customer_id, '商家升级提醒', "恭喜尊敬的用户【{$customer_info['shop_name']}】，您的经验值已达到【{$grade_info['name']}】级别，现已升级为【{$grade_info['name']}】");
    }
    return true;
}

/**
 * 获得批发的商品单价
 * @param int $supply_id 供应产品ID
 * @param int $num 购买数量
 */
function wholesale_goods_price($supply_id, $num) {
    if (!$supply_id || !$num)
        return false;
    $supply_info = M('goods_supply')->where(array('id' => $supply_id))->find();
    if (!$supply_info['inc_wholesale_num'] || !$supply_info['inc_wholesale_price'])
        return $supply_info['wholesale_price'];
    if ($num < $supply_info['wholesale_start_num'])
        return $supply_info['acting_price'];
    $level = floor(( $num - $supply_info['wholesale_start_num'] ) / $supply_info['inc_wholesale_num']); //获得价格的层级
    //判断是否达到追加的条件
    if (!$level)
        return $supply_info['wholesale_price'];
    $price = $supply_info['wholesale_price'] - ( $level * $supply_info['inc_wholesale_price'] );
    //判断是否小最低单价
    if ($price <= 0 || $price <= $supply_info['wholesale_small_price'])
        return $supply_info['wholesale_small_price'];
    return $price;
}

/**
 * 获得锁货的商品单价
 * @param int $supply_id 供应产品ID
 * @param int $num 购买数量
 */
function lock_goods_price($supply_id, $num) {
    if (!$supply_id || !$num)
        return false;
    $supply_info = M('goods_supply')->where(array('id' => $supply_id))->find();
    if (!$supply_info['inc_lock_num'] || !$supply_info['inc_lock_price'])
        return $supply_info['lock_price'];
    $level = floor(( $num - $supply_info['lock_start_num'] ) / $supply_info['inc_lock_num']); //获得价格的层级
    //判断是否达到追加的条件
    if (!$level)
        return $supply_info['lock_price'];
    $price = $supply_info['lock_price'] - ( $level * $supply_info['inc_lock_price'] );
    //判断是否小最低单价
    if ($price <= 0 || $price <= $supply_info['lock_small_price'])
        return $supply_info['lock_small_price'];
    return $price;
}

/**
 * 获得锁货订单应支付金额
 * @param int $order_id 锁货订单ID
 */
function lock_order_pay_price($order_id) {
    if (!$order_id)
        return false;
    $order_info = M('order_goods_distribution_lock')->alias('o')->join('__GOODS_SUPPLY__ gs ON gs.id = o.goods_supply_id')->field('o.total_price,gs.lock_pay_type,gs.lock_pay_rule')->where(array('o.id' => $order_id))->find();
    if (!$order_info) {
        return false;
    }
    switch ($order_info['lock_pay_type']) {
        case '1' :
            return $order_info['total_price'];
            break;
        case '2' :
        case '3' :
            $lock_pay_rule = unserialize($order_info['lock_pay_rule']);
            return number_format($order_info['total_price'] * ( $lock_pay_rule['lock'] / 100 ), 2, '.', '');
            break;
    }
}

/**
 * 获得订单的支付方式
 * @param int $order_id 订单ID
 */
function get_order_pay_model($order_id) {
    if (!$order_id)
        return false;
    //共享库存付款入库
    $order_line = M('order_line')->alias('ol')->join('__GOODS_SUPPLY__ gs ON gs.id = ol.supply_product_id')->where(array('ol.source_type' => 2, 'ol.order_id' => $order_id, 'pay_status' => array('in', array('0', '1'))))
                    ->field('gs.wholesale_pay_type,gs.wholesale_pay_rule,ol.num,ol.price,ol.id,ol.fee')->select();
    if ($order_line) {
        foreach ($order_line as $key => $value) {
            $fee = ($value['fee'] ? $value['fee'] : 0);
            switch ($value['wholesale_pay_type']) {
                case '1' : //一次性支付
                    M('order_line_pay')->add(array(
                        'order_line_id' => $value['id'],
                        'step' => 1,
                        'price' => $value['num'] * $value['price'] + $fee,
                        'scale' => 100
                    ));
                    break;
                case '2' : //分两次支付
                    $wholesale_pay_rule = unserialize($value['wholesale_pay_rule']);
                    for ($i = 1; $i <= 2; $i++) {
                        M('order_line_pay')->add(array(
                            'order_line_id' => $value['id'],
                            'step' => $i,
                            'price' => ( ( $value['num'] * $value['price'] ) + $fee ) * $wholesale_pay_rule[$i == 1 ? 'down' : 'received'] / 100,
                            'scale' => $wholesale_pay_rule[$i == 1 ? 'down' : 'received']
                        ));
                    }
                    break;
            }
        }
    }

    //锁库付款入库 , 'pay_status' => array('in', array('0', '1'))
    $order_line = M('order_line')->alias('ol')->join('__GOODS_DISTRIBUTION__ gd ON gd.id = ol.distribution_product_id')->where(array('ol.source_type' => 1, 'ol.order_id' => $order_id))
                    ->field('gd.pay_rule,ol.num,ol.price,ol.id,ol.fee')->select();

    if ($order_line) {
        foreach ($order_line as $key => $value) {
//            if (!$value['pay_rule']) {
//                M('order_line')->save(array('pay_status' => 2, 'id' => $value['id']));
//            } else {
            $fee = ($value['fee'] ? $value['fee'] : 0);
            $price = $pay_rule ? (( ( $value['num'] * $value['price'] ) + $fee ) * $pay_rule['down'] / 100) : $fee;
            $pay_rule = $value['pay_rule'] ? unserialize($value['pay_rule']) : '';
            if( $price > 0 ) {
                M('order_line_pay')->add(array(
                    'order_line_id' => $value['id'],
                    'step' => 1,
                    'price' => $price,
                    'scale' => $pay_rule['down']
                ));
            }
            
            $price = ( ( $value['num'] * $value['price'] ) + $fee ) * $pay_rule['received'] / 100;
            if (isset($pay_rule['received']) && $price > 0) {
                M('order_line_pay')->add(array(
                    'order_line_id' => $value['id'],
                    'step' => 2,
                    'price' => $price,
                    'scale' => $pay_rule['received']
                ));
            }
//            }
        }
    }
}

/**
 * 获得当前状态下应当支付的金额
 * @param int $order_id
 */
function order_status_surely_pay_price($order_id) {
    if (!$order_id)
        return 0;
    $order_status = M('order_line')->where(array('id' => $order_id))->getField('status');
    if (!is_numeric($order_id))
        return 0;
    switch ($order_status) {
        case '0' :
            $step = 1;
            break;
        case '2' :
            $step = 2;
            break;
    }
    $surely_price = M('order_line_pay')->where(array('order_line_id' => $order_id, 'step' => $step))->getField('price');
    if (!$surely_price)
        return 0;
    return array($surely_price, $step);
}

/**
 * 仓库剩余保存时间
 * @param date $time 时间
 */
function surplus_storage_time($time) {
    if (!$time) {
        return '无';
    }
    $time = ( strtotime($time) - time() );
    $ext = '还剩';
    if ($time < 0) {
        $time = abs($time);
        $ext = '已延期';
    }
    $day = ceil($time / ( 3600 * 24 ));
    if ($day > 1)
        return "{$ext}{$day}天";
    $house = ceil($time / 3600);
    if ($house > 1)
        return "{$ext}{$house}小时";
    $fz = ceil($time / 60);
    return "{$ext}{$fz}分钟";
}

/**
 * 获得仓库过期时间保存的费用
 * @param int $distribution_id 分销ID
 */
function goods_storage_overdue_money($distribution_id) {
    if (!$distribution_id)
        return 0;
    $distribution_info = M('goods_distribution')->alias('gd')->join('__GOODS_SUPPLY__ gs ON gs.id = gd.goods_supply_id')->join('__CUSTOMER_WAREHOUSE__ cw ON cw.id = gs.warehouse_id')
                    ->join('__GOODS__ g ON g.id = gs.goods_id')
                    ->where(array('gd.id' => $distribution_id))->field('gd.storage_end_time,cw.supply_send_day,gd.stock_num,g.weight,cw.storage_overdue_rule')->find();
    if (!$distribution_info)
        return 0;
    $doffer_time = strtotime($distribution_info['storage_end_time']) - time(); //获得延期的秒数
    if ($doffer_time >= 0)
        return 0;
    $doffer_time = abs($doffer_time); //取绝对值
    $save_day = ceil($doffer_time / ( 3600 * 24 )); //获得已经延期的天数
    $goods_weight = $distribution_info['stock_num'] * $distribution_info['weight']; // 获得商品总量
    if (!$distribution_info['storage_overdue_rule'])
        return 0;
    $storage_overdue_rule = unserialize($distribution_info['storage_overdue_rule']); //转换
    return ceil($goods_weight / $storage_overdue_rule['weight']) * $storage_overdue_rule['price'] * $save_day; //获得商品延期总金额
}

/**
 * 总量单位换算
 * @param int $num 数量
 */
function weight_unit_conversion($num) {
    if (!$num)
        return '无';
    if ($num < 1000)
        return $num . 'g';
    if ($num < 1000000)
        return round($num / 1000, 2) . 'kg';
    return round($num / 1000000, 2) . 'T';
}
